{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0feebe54-8083-4c6e-b0de-c9661ae83c57",
   "metadata": {},
   "source": [
    "- https://github.com/langchain-ai/langgraph/blob/main/docs/docs/tutorials/chatbot-simulation-evaluation/agent-simulation-evaluation.ipynb\n",
    "- 左右互博，角色扮演；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d02be709-422a-4fae-a2ee-7e5f617fae76",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:14:20.882446Z",
     "iopub.status.busy": "2024-11-10T14:14:20.882199Z",
     "iopub.status.idle": "2024-11-10T14:14:20.891580Z",
     "shell.execute_reply": "2024-11-10T14:14:20.889982Z",
     "shell.execute_reply.started": "2024-11-10T14:14:20.882422Z"
    }
   },
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv\n",
    "assert load_dotenv()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "f8597b00-1b36-4ec8-9ed4-c1c0821a0459",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:24:51.883698Z",
     "iopub.status.busy": "2024-11-10T14:24:51.883088Z",
     "iopub.status.idle": "2024-11-10T14:24:51.957792Z",
     "shell.execute_reply": "2024-11-10T14:24:51.956167Z",
     "shell.execute_reply.started": "2024-11-10T14:24:51.883647Z"
    }
   },
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import openai\n",
    "from langchain_core.messages import HumanMessage, AIMessage\n",
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_community.adapters.openai import convert_message_to_dict\n",
    "\n",
    "from langgraph.graph import END, StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "from typing import Annotated\n",
    "from typing_extensions import TypedDict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5d9b68f8-b4e8-486d-bc3d-04abd959cf20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:14:25.616447Z",
     "iopub.status.busy": "2024-11-10T14:14:25.615849Z",
     "iopub.status.idle": "2024-11-10T14:14:25.626248Z",
     "shell.execute_reply": "2024-11-10T14:14:25.624384Z",
     "shell.execute_reply.started": "2024-11-10T14:14:25.616396Z"
    }
   },
   "outputs": [],
   "source": [
    "# This is flexible, but you can define your agent here, or call your agent API here.\n",
    "def my_chat_bot(messages: List[dict]) -> dict:\n",
    "    system_message = {\n",
    "        \"role\": \"system\",\n",
    "        \"content\": \"You are a customer support agent for an airline.\",\n",
    "    }\n",
    "    messages = [system_message] + messages\n",
    "    completion = openai.chat.completions.create(\n",
    "        messages=messages, model=\"gpt-3.5-turbo\"\n",
    "    )\n",
    "    return completion.choices[0].message.model_dump()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b5bdab6e-1c12-45a2-8619-5887a9226c5b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:14:57.275040Z",
     "iopub.status.busy": "2024-11-10T14:14:57.274418Z",
     "iopub.status.idle": "2024-11-10T14:14:58.672763Z",
     "shell.execute_reply": "2024-11-10T14:14:58.670520Z",
     "shell.execute_reply.started": "2024-11-10T14:14:57.274971Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'content': \"Hello! Welcome to our airline's customer support. How can I assist you today?\",\n",
       " 'refusal': None,\n",
       " 'role': 'assistant',\n",
       " 'function_call': None,\n",
       " 'tool_calls': None}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_chat_bot([{\"role\": \"user\", \"content\": \"hi!\"}])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6a53cfb-9b25-4c5e-80d4-8f80d9cfb51a",
   "metadata": {},
   "source": [
    "#### Define Simulated User"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cc74f808-9eac-44a6-a2cc-d6e415078df4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:16:32.820410Z",
     "iopub.status.busy": "2024-11-10T14:16:32.819799Z",
     "iopub.status.idle": "2024-11-10T14:16:33.586233Z",
     "shell.execute_reply": "2024-11-10T14:16:33.584813Z",
     "shell.execute_reply.started": "2024-11-10T14:16:32.820357Z"
    }
   },
   "outputs": [],
   "source": [
    "system_prompt_template = \"\"\"You are a customer of an airline company. \\\n",
    "You are interacting with a user who is a customer support person. \\\n",
    "\n",
    "{instructions}\n",
    "\n",
    "When you are finished with the conversation, respond with a single word 'FINISHED'\"\"\"\n",
    "\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", system_prompt_template),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "70a9f65a-3707-4214-88fb-f150eaa5f337",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:16:41.155181Z",
     "iopub.status.busy": "2024-11-10T14:16:41.154594Z",
     "iopub.status.idle": "2024-11-10T14:16:41.163359Z",
     "shell.execute_reply": "2024-11-10T14:16:41.161744Z",
     "shell.execute_reply.started": "2024-11-10T14:16:41.155129Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m System Message \u001b[0m================================\n",
      "\n",
      "You are a customer of an airline company. You are interacting with a user who is a customer support person. \n",
      "\u001b[33;1m\u001b[1;3m{instructions}\u001b[0m\n",
      "\n",
      "When you are finished with the conversation, respond with a single word 'FINISHED'\n",
      "\n",
      "=============================\u001b[1m Messages Placeholder \u001b[0m=============================\n",
      "\n",
      "\u001b[33;1m\u001b[1;3m{messages}\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "prompt.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "449ea63c-91fb-4465-ba01-f7496a852df7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:17:48.318294Z",
     "iopub.status.busy": "2024-11-10T14:17:48.317662Z",
     "iopub.status.idle": "2024-11-10T14:17:48.330818Z",
     "shell.execute_reply": "2024-11-10T14:17:48.328924Z",
     "shell.execute_reply.started": "2024-11-10T14:17:48.318241Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatPromptTemplate(input_variables=['messages'], input_types={'messages': list[typing.Annotated[typing.Union[typing.Annotated[langchain_core.messages.ai.AIMessage, Tag(tag='ai')], typing.Annotated[langchain_core.messages.human.HumanMessage, Tag(tag='human')], typing.Annotated[langchain_core.messages.chat.ChatMessage, Tag(tag='chat')], typing.Annotated[langchain_core.messages.system.SystemMessage, Tag(tag='system')], typing.Annotated[langchain_core.messages.function.FunctionMessage, Tag(tag='function')], typing.Annotated[langchain_core.messages.tool.ToolMessage, Tag(tag='tool')], typing.Annotated[langchain_core.messages.ai.AIMessageChunk, Tag(tag='AIMessageChunk')], typing.Annotated[langchain_core.messages.human.HumanMessageChunk, Tag(tag='HumanMessageChunk')], typing.Annotated[langchain_core.messages.chat.ChatMessageChunk, Tag(tag='ChatMessageChunk')], typing.Annotated[langchain_core.messages.system.SystemMessageChunk, Tag(tag='SystemMessageChunk')], typing.Annotated[langchain_core.messages.function.FunctionMessageChunk, Tag(tag='FunctionMessageChunk')], typing.Annotated[langchain_core.messages.tool.ToolMessageChunk, Tag(tag='ToolMessageChunk')]], FieldInfo(annotation=NoneType, required=True, discriminator=Discriminator(discriminator=<function _get_type at 0x7433a24cc720>, custom_error_type=None, custom_error_message=None, custom_error_context=None))]]}, partial_variables={'name': 'Harrison', 'instructions': 'Your name is Harrison. You are trying to get a refund for the trip you took to Alaska. You want them to give you ALL the money back. This trip happened 5 years ago.'}, messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['instructions'], input_types={}, partial_variables={}, template=\"You are a customer of an airline company. You are interacting with a user who is a customer support person. \\n{instructions}\\n\\nWhen you are finished with the conversation, respond with a single word 'FINISHED'\"), additional_kwargs={}), MessagesPlaceholder(variable_name='messages')])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "instructions = \"\"\"Your name is Harrison. You are trying to get a refund for the trip you took to Alaska. \\\n",
    "You want them to give you ALL the money back. \\\n",
    "This trip happened 5 years ago.\"\"\"\n",
    "\n",
    "prompt = prompt.partial(instructions=instructions)\n",
    "\n",
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "fac8c452-30b4-45a9-b5dc-139909b90f89",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:18:32.348696Z",
     "iopub.status.busy": "2024-11-10T14:18:32.348093Z",
     "iopub.status.idle": "2024-11-10T14:18:32.457602Z",
     "shell.execute_reply": "2024-11-10T14:18:32.456019Z",
     "shell.execute_reply.started": "2024-11-10T14:18:32.348641Z"
    }
   },
   "outputs": [],
   "source": [
    "model = ChatOpenAI(model='gpt-4o-2024-08-06')\n",
    "simulated_user = prompt | model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9046e850-13e9-4624-b9d6-6f471772a811",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:21:20.020978Z",
     "iopub.status.busy": "2024-11-10T14:21:20.020413Z",
     "iopub.status.idle": "2024-11-10T14:21:20.066727Z",
     "shell.execute_reply": "2024-11-10T14:21:20.064783Z",
     "shell.execute_reply.started": "2024-11-10T14:21:20.020927Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatPromptValue</span><span style=\"font-weight: bold\">(</span>\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   </span><span style=\"color: #808000; text-decoration-color: #808000\">messages</span>=<span style=\"font-weight: bold\">[</span>\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   │   </span><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">SystemMessage</span><span style=\"font-weight: bold\">(</span>\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   │   │   </span><span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #008000; text-decoration-color: #008000\">\"You are a customer of an airline company. You are interacting with a user who is a customer support person. \\nYour name is Harrison. You are trying to get a refund for the trip you took to Alaska. You want them to give you ALL the money back. This trip happened 5 years ago.\\n\\nWhen you are finished with the conversation, respond with a single word 'FINISHED'\"</span>,\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   │   │   </span><span style=\"color: #808000; text-decoration-color: #808000\">additional_kwargs</span>=<span style=\"font-weight: bold\">{}</span>,\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   │   │   </span><span style=\"color: #808000; text-decoration-color: #808000\">response_metadata</span>=<span style=\"font-weight: bold\">{}</span>\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   │   </span><span style=\"font-weight: bold\">)</span>,\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   │   </span><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">HumanMessage</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'Hi! How can I help you?'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">additional_kwargs</span>=<span style=\"font-weight: bold\">{}</span>, <span style=\"color: #808000; text-decoration-color: #808000\">response_metadata</span>=<span style=\"font-weight: bold\">{})</span>\n",
       "<span style=\"color: #7fbf7f; text-decoration-color: #7fbf7f\">│   </span><span style=\"font-weight: bold\">]</span>\n",
       "<span style=\"font-weight: bold\">)</span>\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\u001b[1;35mChatPromptValue\u001b[0m\u001b[1m(\u001b[0m\n",
       "\u001b[2;32m│   \u001b[0m\u001b[33mmessages\u001b[0m=\u001b[1m[\u001b[0m\n",
       "\u001b[2;32m│   │   \u001b[0m\u001b[1;35mSystemMessage\u001b[0m\u001b[1m(\u001b[0m\n",
       "\u001b[2;32m│   │   │   \u001b[0m\u001b[33mcontent\u001b[0m=\u001b[32m\"You\u001b[0m\u001b[32m are a customer of an airline company. You are interacting with a user who is a customer support person. \\nYour name is Harrison. You are trying to get a refund for the trip you took to Alaska. You want them to give you ALL the money back. This trip happened 5 years ago.\\n\\nWhen you are finished with the conversation, respond with a single word 'FINISHED'\"\u001b[0m,\n",
       "\u001b[2;32m│   │   │   \u001b[0m\u001b[33madditional_kwargs\u001b[0m=\u001b[1m{\u001b[0m\u001b[1m}\u001b[0m,\n",
       "\u001b[2;32m│   │   │   \u001b[0m\u001b[33mresponse_metadata\u001b[0m=\u001b[1m{\u001b[0m\u001b[1m}\u001b[0m\n",
       "\u001b[2;32m│   │   \u001b[0m\u001b[1m)\u001b[0m,\n",
       "\u001b[2;32m│   │   \u001b[0m\u001b[1;35mHumanMessage\u001b[0m\u001b[1m(\u001b[0m\u001b[33mcontent\u001b[0m=\u001b[32m'Hi! How can I help you?'\u001b[0m, \u001b[33madditional_kwargs\u001b[0m=\u001b[1m{\u001b[0m\u001b[1m}\u001b[0m, \u001b[33mresponse_metadata\u001b[0m=\u001b[1m{\u001b[0m\u001b[1m}\u001b[0m\u001b[1m)\u001b[0m\n",
       "\u001b[2;32m│   \u001b[0m\u001b[1m]\u001b[0m\n",
       "\u001b[1m)\u001b[0m\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from rich.pretty import pprint\n",
    "pprint(prompt.invoke({'messages': [HumanMessage(content='Hi! How can I help you?')]}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "79b3cb6b-ffad-4143-a938-069849b103c2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:21:35.452606Z",
     "iopub.status.busy": "2024-11-10T14:21:35.451979Z",
     "iopub.status.idle": "2024-11-10T14:21:36.897101Z",
     "shell.execute_reply": "2024-11-10T14:21:36.895360Z",
     "shell.execute_reply.started": "2024-11-10T14:21:35.452555Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content=\"Hi, I'm looking to get a refund for a trip I took to Alaska a while back. I believe I should be entitled to a full refund. Can you assist me with this?\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 37, 'prompt_tokens': 98, 'total_tokens': 135, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_159d8341cc', 'finish_reason': 'stop', 'logprobs': None}, id='run-da7a524b-2e50-4e26-bf04-71dd26b8540c-0', usage_metadata={'input_tokens': 98, 'output_tokens': 37, 'total_tokens': 135})"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "simulated_user.invoke({'messages': [HumanMessage(content='Hi! How can I help you?')]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed120510-a46d-4c6c-8fe7-7dadf484e5df",
   "metadata": {},
   "source": [
    "#### Define the Agent Simulation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "0c69db7c-0620-4f84-81ad-fb77489ac660",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:23:22.833907Z",
     "iopub.status.busy": "2024-11-10T14:23:22.833279Z",
     "iopub.status.idle": "2024-11-10T14:23:22.844259Z",
     "shell.execute_reply": "2024-11-10T14:23:22.842052Z",
     "shell.execute_reply.started": "2024-11-10T14:23:22.833851Z"
    }
   },
   "outputs": [],
   "source": [
    "def chat_bot_node(state):\n",
    "    messages = state[\"messages\"]\n",
    "    # Convert from LangChain format to the OpenAI format, which our chatbot function expects.\n",
    "    messages = [convert_message_to_dict(m) for m in messages]\n",
    "    # Call the chat bot\n",
    "    chat_bot_response = my_chat_bot(messages)\n",
    "    # Respond with an AI Message\n",
    "    return {\"messages\": [AIMessage(content=chat_bot_response[\"content\"])]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "8b2c4d19-eec6-4083-b614-c28c29878f0f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:23:37.947615Z",
     "iopub.status.busy": "2024-11-10T14:23:37.947012Z",
     "iopub.status.idle": "2024-11-10T14:23:37.956832Z",
     "shell.execute_reply": "2024-11-10T14:23:37.954931Z",
     "shell.execute_reply.started": "2024-11-10T14:23:37.947565Z"
    }
   },
   "outputs": [],
   "source": [
    "def _swap_roles(messages):\n",
    "    new_messages = []\n",
    "    for m in messages:\n",
    "        if isinstance(m, AIMessage):\n",
    "            new_messages.append(HumanMessage(content=m.content))\n",
    "        else:\n",
    "            new_messages.append(AIMessage(content=m.content))\n",
    "    return new_messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "f7bcd91e-9da9-4707-ba5b-11def0d93f97",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:24:13.444442Z",
     "iopub.status.busy": "2024-11-10T14:24:13.443810Z",
     "iopub.status.idle": "2024-11-10T14:24:13.454085Z",
     "shell.execute_reply": "2024-11-10T14:24:13.452167Z",
     "shell.execute_reply.started": "2024-11-10T14:24:13.444391Z"
    }
   },
   "outputs": [],
   "source": [
    "def simulated_user_node(state):\n",
    "    messages = state[\"messages\"]\n",
    "    # Swap roles of messages\n",
    "    new_messages = _swap_roles(messages)\n",
    "    # Call the simulated user\n",
    "    response = simulated_user.invoke({\"messages\": new_messages})\n",
    "    # This response is an AI message - we need to flip this to be a human message\n",
    "    return {\"messages\": [HumanMessage(content=response.content)]}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d2a9947-70cb-4fc2-967c-c2839c248428",
   "metadata": {},
   "source": [
    "#### define the edges"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "2bb085bd-bba8-4744-b130-4ff51d75679e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:24:31.592668Z",
     "iopub.status.busy": "2024-11-10T14:24:31.592060Z",
     "iopub.status.idle": "2024-11-10T14:24:31.601549Z",
     "shell.execute_reply": "2024-11-10T14:24:31.599896Z",
     "shell.execute_reply.started": "2024-11-10T14:24:31.592616Z"
    }
   },
   "outputs": [],
   "source": [
    "def should_continue(state):\n",
    "    messages = state[\"messages\"]\n",
    "    if len(messages) > 6:\n",
    "        return \"end\"\n",
    "    elif messages[-1].content == \"FINISHED\":\n",
    "        return \"end\"\n",
    "    else:\n",
    "        return \"continue\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fefef3e0-cb13-4e75-a383-ade199807610",
   "metadata": {},
   "source": [
    "#### graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "8cdab327-06c4-428f-afb1-6fd3ba5905b1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:25:14.695830Z",
     "iopub.status.busy": "2024-11-10T14:25:14.695269Z",
     "iopub.status.idle": "2024-11-10T14:25:14.710492Z",
     "shell.execute_reply": "2024-11-10T14:25:14.708711Z",
     "shell.execute_reply.started": "2024-11-10T14:25:14.695783Z"
    }
   },
   "outputs": [],
   "source": [
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "graph_builder.add_node(\"user\", simulated_user_node)\n",
    "graph_builder.add_node(\"chat_bot\", chat_bot_node)\n",
    "# Every response from  your chat bot will automatically go to the\n",
    "# simulated user\n",
    "graph_builder.add_edge(\"chat_bot\", \"user\")\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"user\",\n",
    "    should_continue,\n",
    "    # If the finish criteria are met, we will stop the simulation,\n",
    "    # otherwise, the virtual user's message will be sent to your chat bot\n",
    "    {\n",
    "        \"end\": END,\n",
    "        \"continue\": \"chat_bot\",\n",
    "    },\n",
    ")\n",
    "# The input will first go to your chat bot\n",
    "graph_builder.add_edge(START, \"chat_bot\")\n",
    "simulation = graph_builder.compile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "0797bc33-85ed-4cee-afd1-c1032adf35a3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:25:29.933922Z",
     "iopub.status.busy": "2024-11-10T14:25:29.933297Z",
     "iopub.status.idle": "2024-11-10T14:25:39.794931Z",
     "shell.execute_reply": "2024-11-10T14:25:39.792950Z",
     "shell.execute_reply.started": "2024-11-10T14:25:29.933868Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'chat_bot': {'messages': [AIMessage(content='Hello! How can I assist you today?', additional_kwargs={}, response_metadata={}, id='1102460a-3f29-42ab-86ed-36bbe75404e3')]}}\n",
      "----\n",
      "{'user': {'messages': [HumanMessage(content=\"Hi, I'm looking to get a refund for a trip I took to Alaska. Could you help me with that?\", additional_kwargs={}, response_metadata={}, id='3642dbba-06f6-462c-9657-02b1502029b2')]}}\n",
      "----\n",
      "{'chat_bot': {'messages': [AIMessage(content=\"I'd be happy to help you with that. Can you please provide me with your booking reference or ticket number so I can look up your reservation?\", additional_kwargs={}, response_metadata={}, id='9be2b7ad-a3e1-41fe-86d7-303828262446')]}}\n",
      "----\n",
      "{'user': {'messages': [HumanMessage(content=\"I'm afraid I don't have the booking reference or ticket number anymore. The trip was about 5 years ago. Can you still help me with the refund?\", additional_kwargs={}, response_metadata={}, id='13b11570-259e-4510-9b11-ae2f62aa6604')]}}\n",
      "----\n",
      "{'chat_bot': {'messages': [AIMessage(content='I understand your situation. Without the booking reference or ticket number, it may be challenging to locate your specific reservation. However, I recommend contacting our customer service team directly to explain your situation. They may be able to assist you further with the refund process. Thank you for your understanding.', additional_kwargs={}, response_metadata={}, id='839f3ab3-6742-46f7-afc4-9de4799a1520')]}}\n",
      "----\n",
      "{'user': {'messages': [HumanMessage(content=\"I appreciate that, but I really need to get a full refund for this trip. Isn't there any way you can process it without the booking details? It was quite a while ago, but I believe I should be able to get all my money back.\", additional_kwargs={}, response_metadata={}, id='126f0934-1d0b-4d55-bfae-23e509e28d23')]}}\n",
      "----\n",
      "{'chat_bot': {'messages': [AIMessage(content='I apologize for the inconvenience. Since the trip was taken five years ago, processing a refund without the booking details may be challenging. However, I suggest providing any additional information you remember about the trip, such as the dates, destinations, or the name of the passengers, to our customer service team when you contact them. They may be able to assist you further in locating your reservation and processing the refund. Thank you for your patience and understanding.', additional_kwargs={}, response_metadata={}, id='b2be2def-faaa-4e1e-a814-eb47519b254b')]}}\n",
      "----\n",
      "{'user': {'messages': [HumanMessage(content=\"I understand, but I'm really hoping there is a way to get the full refund processed. I'll try to gather as much information as I can and reach out to the customer service team as you suggested. Thank you for your help.\", additional_kwargs={}, response_metadata={}, id='92cee34e-84c8-45ed-8d43-b3a5cc9a5f21')]}}\n",
      "----\n"
     ]
    }
   ],
   "source": [
    "for chunk in simulation.stream({\"messages\": []}):\n",
    "    # Print out all events aside from the final end chunk\n",
    "    if END not in chunk:\n",
    "        print(chunk)\n",
    "        print(\"----\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "641befdd-ed21-4e96-9002-83b5d1bff500",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "agent",
   "language": "python",
   "name": "agent"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
